#ifndef RS485_DRIVER
#define RS485_DRIVER

#ifndef RS485_ID
#define RS485_ID  0x10                 // The device's RS485 address or ID
#endif

#ifndef RS485_RX_PIN
#define RS485_RX_PIN       PIN_B1   // Data receive pin
#endif

#ifndef RS485_TX_PIN
#define RS485_TX_PIN       PIN_B2   // Data transmit pin
#endif

#ifndef RS485_ENABLE_PIN
#define RS485_ENABLE_PIN   PIN_A1   // Controls DE pin.  RX low, TX high.
#endif

#use rs232(baud=9600, xmit=RS485_TX_PIN, rcv=RS485_RX_PIN, bits=8, stream=RS485)

#define RS485_wait_time 20             // Wait time in milliseconds

//#bit    rs485_collision = rs232_errors.6

#ifndef RS485_BUFFER_SIZE
#define RS485_BUFFER_SIZE  40
#endif

unsigned int8 rs485_buffersz;
unsigned char rs485_buffer[RS485_BUFFER_SIZE];
unsigned int rs485_hasMsg;

void rs485_init()
{
   output_low(RS485_ENABLE_PIN);
   rs485_buffersz=0;
   rs485_hasMsg=FALSE;
   while(kbhit(RS485)) fgetc(RS485);
}

void getRDA()
{
   char c;
   //output_toggle(pin_a2);
   c = fgetc(RS485);
   if(rs485_buffersz==0 && c!='$') return;
   if(rs485_buffersz >0 && c=='$') rs485_buffersz=0; // descartar msg anterior
   if(rs485_buffersz>=RS485_BUFFER_SIZE) rs485_buffersz=0; // pra nao estourar o buffer
   rs485_buffer[rs485_buffersz++] = c;
   
   if(rs485_buffersz>4 && (rs485_buffer[1]+5)<=rs485_buffersz && rs485_buffer[rs485_buffer[1]+4]=='#')
   {
      rs485_hasMsg=true;
   }
}

int8 rs485_get_message(int8* data)
{
   int8 i;
   
   while(kbhit(RS485)) getRDA();
   if(!rs485_hasMsg) return 0;
   
   for(i=0; i<rs485_buffersz; ++i,++data)
   {
      *data = rs485_buffer[i];
   }

   rs485_hasMsg=FALSE;
   i=rs485_buffersz;
   rs485_buffersz=0;
   
   return i;
}

int1 rs485_send_message(int8 to, int8 len, int8* data)
{
   int8 i;

   output_high(RS485_ENABLE_PIN);
   fputc('$', RS485);
   fputc(len, RS485);
   fputc(RS485_ID, RS485);
   fputc(to, RS485);

   for(i=0; i<len; ++i)
   {
      fputc(*data, RS485);
      ++data;
   }

   fputc('#', RS485);
   delay_ms(10);
   output_low(RS485_ENABLE_PIN);
   return TRUE;
}

